package cn.javabb.core.service.sys;


import cn.javabb.common.utils.ListUtils;
import cn.javabb.core.base.BaseService;
import cn.javabb.core.entity.sys.RolePermissionsDO;
import com.alibaba.druid.util.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class RolePermissionService extends BaseService<RolePermissionsDO> {
    /**
     * 根据角色ID获取角色的权限
     * @param roleId
     * @return
     */
    public List<RolePermissionsDO> listByRoleId(Integer roleId,Integer type){
        RolePermissionsDO rp = new RolePermissionsDO().setRoleId(roleId).setPermissionType(type);
        return this.queryListByWhere(rp);
    }

    /**
     * 更新角色权限
     *
     * @author QINB
     * @param roleId
     * @param permissionIds
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean saveRolePermissions(Integer roleId,Integer permissionType, String permissionIds) {
        RolePermissionsDO rp = new RolePermissionsDO();
        rp.setRoleId(roleId);
        rp.setPermissionType(permissionType);
        this.deleteByWhere(rp);

        if (!StringUtils.isEmpty(permissionIds)) {
            List<RolePermissionsDO> rpList = new ArrayList<>();
            List<String> idList = ListUtils.stringToListString(permissionIds);
            for (String id : idList) {
                rpList.add(new RolePermissionsDO()
                        .setRoleId(roleId)
                        .setPermissionId(Integer.parseInt(id))
                        .setPermissionType(permissionType));
            }
            this.insertList(rpList);
        }
        return true;
    }
    /*删除角色权限*/
    public boolean deleteByRoleId(Integer roleId) {
        RolePermissionsDO rp = new RolePermissionsDO().setRoleId(roleId);
        return this.deleteByWhere(rp) > 0;
    }
}
